const router = require("koa-router")();
const articleList = require("../mock/article.json");
const dayjs = require("dayjs");
const fs = require("fs");

router.post("/article", (ctx) => {
  const { title, titleImage, content, auther, type, avatar, description } =
    ctx.request.body;

  const data = {
    title,
    titleImage,
    content,
    auther,
    type,
    avatar,
    description,
    createTime: dayjs().format("YYYY-MM-DD hh-mm-ss"),
    lastUpdateTime: dayjs().format("YYYY-MM-DD hh-mm-ss"),
    commentList: [],
    lookCount: 0,
    goodLike: 0,
    dotLike: 0,
    id: new Date().getTime(),
  };

  articleList.push(data);

  fs.writeFileSync("mock/article.json", JSON.stringify(articleList));
  ctx.body = {
    code: 200,
    message: "添加成功",
  };
});

router.get("/article", (ctx) => {
  ctx.body = {
    code: 200,
    data: articleList,
    messasge: "文章列表获取成功",
  };
});

router.get("/article/:id", (ctx) => {
  const { id } = ctx.params;
  const item = articleList.find((v) => v.id === +id);

  ctx.body = {
    data: item,
    code: 200,
    message: "详情数据获取成功",
  };
});

module.exports = router;
